"""
认证API
处理用户登录、注册和令牌刷新
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import (
    create_access_token, get_jwt_identity, jwt_required
)

from app.models.user import User
from app.schemas.user import UserSchema
from app.extensions import db

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    data = request.get_json()
    
    if not data or not data.get('username') or not data.get('password'):
        return jsonify({"error": "请提供用户名和密码"}), 400
    
    user = User.query.filter_by(username=data.get('username')).first()
    
    if not user or not user.check_password(data.get('password')):
        return jsonify({"error": "用户名或密码错误"}), 401
    
    if not user.is_active:
        return jsonify({"error": "用户已被禁用"}), 403
    
    # 创建访问令牌
    access_token = create_access_token(identity=user.id)
    
    return jsonify({
        "access_token": access_token,
        "user": {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "role": user.role,
            "full_name": user.full_name
        }
    }), 200

@auth_bp.route('/refresh', methods=['POST'])
@jwt_required()
def refresh():
    """刷新访问令牌"""
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user or not user.is_active:
        return jsonify({"error": "用户不存在或已被禁用"}), 401
    
    # 创建新的访问令牌
    access_token = create_access_token(identity=current_user_id)
    
    return jsonify({"access_token": access_token}), 200

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def profile():
    """获取当前用户资料"""
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({"msg": "用户不存在"}), 404
    
    return jsonify(UserSchema().dump(user)), 200

@auth_bp.route('/change-password', methods=['PUT'])
@jwt_required()
def change_password():
    """修改密码"""
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({"msg": "用户不存在"}), 404
    
    data = request.get_json()
    old_password = data.get('old_password')
    new_password = data.get('new_password')
    
    if not old_password or not new_password:
        return jsonify({"msg": "请提供旧密码和新密码"}), 400
    
    if not user.check_password(old_password):
        return jsonify({"msg": "旧密码不正确"}), 401
    
    user.set_password(new_password)
    db.session.commit()
    
    return jsonify({"msg": "密码修改成功"}), 200 